<template>
  <view class="add-container">
    <!-- 主页面 -->
    <view v-if="!showSpecial" class="main-content">
      <scroll-view 
        scroll-y 
        refresher-enabled
        :refresher-triggered="refreshing"
        @refresherrefresh="onRefresh"
        class="scroll-view"
      >
        <view class="section-title">选择工件</view>
        
        <!-- 工件选择器 -->
        <view class="work-item-selector">
          <view class="selector-input" @tap="showWorkItemPicker">
            <text class="placeholder" v-if="!selectedItem">请选择工件</text>
            <view class="selected-item" v-else>
              <text class="name">{{ selectedItem.name }}</text>
              <text class="price">¥{{ selectedItem.price }}/个</text>
            </view>
            <text class="arrow">▼</text>
          </view>
        </view>
        
        <!-- 工件选择弹窗 -->
        <uni-popup ref="workItemPopup" type="bottom">
          <view class="picker-popup">
            <view class="popup-header">
              <text class="title">选择工件</text>
              <text class="close" @tap="closeWorkItemPicker">×</text>
            </view>
            
            <!-- 搜索框 -->
            <view class="search-box">
              <input 
                type="text"
                v-model="searchKeyword"
                placeholder="搜索工件"
                @input="handleSearch"
              />
            </view>
            
            <!-- 工件列表 -->
            <scroll-view 
              scroll-y 
              class="work-items-list"
              :style="{ height: '60vh' }"
            >
              <view 
                v-for="item in filteredWorkItems" 
                :key="item.id"
                class="work-item"
                :class="{ 'active': selectedItem?.id === item.id }"
                @tap="selectItem(item)"
              >
                <view class="item-info">
                  <text class="name">{{ item.name }}</text>
                  <text class="price">¥{{ item.price }}/个</text>
                </view>
                <text class="check-icon" v-if="selectedItem?.id === item.id">✓</text>
              </view>
            </scroll-view>
            
            <view class="popup-footer">
              <button class="confirm-btn" @tap="confirmSelection">确认选择</button>
            </view>
          </view>
        </uni-popup>
        
        <!-- 数量输入 -->
        <view class="input-section" v-if="selectedItem">
          <view class="section-title">数量</view>
          <view class="quantity-input">
            <text class="minus" @tap="handleMinus">-</text>
            <input 
              type="number" 
              v-model="quantity"
              @input="handleQuantityInput"
            />
            <text class="plus" @tap="handlePlus">+</text>
          </view>
        </view>
        
        <!-- 备注输入 -->
        <view class="input-section" v-if="selectedItem">
          <view class="section-title">备注</view>
          <textarea 
            v-model="remark"
            class="remark-input"
            placeholder="请输入备注信息(选填)"
          />
        </view>
        
        <!-- 提交按钮 -->
        <view class="button-group">
          <button 
            class="submit-btn"
            :disabled="!canSubmit"
            :loading="submitting"
            @tap="handleSubmit"
          >
            {{ submitting ? '提交中...' : '确认添加' }}
          </button>
          
          <button 
            class="special-btn"
            @tap="showSpecialPage"
          >
            特殊添加
          </button>
        </view>
      </scroll-view>
    </view>
    
    <!-- 特殊工作记录页面 -->
    <view v-else class="special-content">
      <view class="page-header">
        <button class="back-btn" @tap="hideSpecialPage">
          <text class="back-icon">←</text>
          <text>返回</text>
        </button>
        <text class="title">特殊工作</text>
      </view>
      
      <view class="input-section">
        <view class="section-title">工作内容</view>
        <input 
          type="text"
          v-model="specialForm.name"
          class="content-input"
          placeholder="请输入工作内容"
        />
      </view>

      <view class="input-section">
        <view class="section-title">数量</view>
        <input 
          type="number"
          v-model="specialForm.quantity"
          class="quantity-input"
          placeholder="请输入数量"
        />
      </view>
      
      <view class="input-section">
        <view class="section-title">应得报酬(元)</view>
        <input 
          type="digit"
          v-model="specialForm.price"
          class="price-input"
          placeholder="请输入应得报酬"
        />
      </view>

      <view class="input-section">
        <view class="section-title">记录时间</view>
        <uni-datetime-picker 
          type="date" 
          v-model="specialForm.date"
          :end="today"
        />
      </view>
      
      <view class="input-section">
        <view class="section-title">备注</view>
        <textarea 
          v-model="specialForm.remark"
          class="remark-input"
          placeholder="请输入备注信息(选填)"
        />
      </view>
      
      <button 
        class="submit-btn"
        :disabled="!canSubmitSpecial"
        :loading="submitting"
        @tap="handleSpecialSubmit"
      >
        {{ submitting ? '提交中...' : '确认添加' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import workItem from '@/api/workItem'
import dayjs from 'dayjs'

// 状态
const showSpecial = ref(false)
const workItems = ref([])
const selectedItem = ref(null)
const quantity = ref(1)
const remark = ref('')
const submitting = ref(false)
const refreshing = ref(false)

// 特殊工作表单
const specialForm = ref({
  name: '',
  quantity: '',
  price: '',
  date: dayjs().format('YYYY-MM-DD'),
  remark: ''
})

// 获取今天的日期
const today = dayjs().format('YYYY-MM-DD')

// 添加新的状态
const workItemPopup = ref(null)
const searchKeyword = ref('')

// 计算属性
const canSubmit = computed(() => {
  return selectedItem.value && quantity.value > 0
})

const canSubmitSpecial = computed(() => {
  return specialForm.value.name && 
         specialForm.value.quantity && 
         Number(specialForm.value.quantity) > 0 &&
         specialForm.value.price && 
         Number(specialForm.value.price) > 0 &&
         specialForm.value.date
})

// 计算过滤后的工件列表
const filteredWorkItems = computed(() => {
  if (!searchKeyword.value) return workItems.value
  
  const keyword = searchKeyword.value.toLowerCase()
  return workItems.value.filter(item => 
    item.name.toLowerCase().includes(keyword)
  )
})

// 获取工件列表
async function fetchWorkItems() {
  try {
    const res = await workItem.getList()
    workItems.value = res
  } catch (error) {
    uni.showToast({
      title: '获取工件列表失败',
      icon: 'none'
    })
  }
}

// 显示工件选择器
function showWorkItemPicker() {
  workItemPopup.value.open()
}

// 关闭工件选择器
function closeWorkItemPicker() {
  workItemPopup.value.close()
  searchKeyword.value = ''
}

// 选择工件
function selectItem(item) {
  selectedItem.value = item
}

// 确认选择
function confirmSelection() {
  if (selectedItem.value) {
    closeWorkItemPicker()
  } else {
    uni.showToast({
      title: '请选择工件',
      icon: 'none'
    })
  }
}

// 处理搜索
function handleSearch() {
  // 搜索功能已通过计算属性实现
}

// 处理数量输入
function handleQuantityInput(e) {
  const val = parseInt(e.detail.value)
  if (isNaN(val) || val < 1) {
    quantity.value = 1
  } else {
    quantity.value = val
  }
}

// 减少数量
function handleMinus() {
  if (quantity.value > 1) {
    quantity.value--
  }
}

// 增加数量
function handlePlus() {
  quantity.value++
}

// 显示特殊工作页面
function showSpecialPage() {
  showSpecial.value = true
}

// 隐藏特殊工作页面
function hideSpecialPage() {
  showSpecial.value = false
  // 重置表单
  specialForm.value = {
    name: '',
    quantity: '',
    price: '',
    date: dayjs().format('YYYY-MM-DD'),
    remark: ''
  }
}

// 提交普通工作记录
async function handleSubmit() {
  if (!canSubmit.value || submitting.value) return
  
  try {
    submitting.value = true
    await workItem.addRecord({
      workItemId: selectedItem.value.id,
      quantity: quantity.value,
      remark: remark.value
    })
    
    uni.showToast({
      title: '添加成功',
      icon: 'success'
    })
    
    // 重置表单
    selectedItem.value = null
    quantity.value = 1
    remark.value = ''
  } catch (error) {
    uni.showToast({
      title: error.message || '添加失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 提交特殊工作记录
async function handleSpecialSubmit() {
  if (!canSubmitSpecial.value || submitting.value) return
  
  try {
    submitting.value = true
    await workItem.addSpecialRecord({
      name: specialForm.value.name,
      quantity: Number(specialForm.value.quantity),
      price: Number(specialForm.value.price),
      date: specialForm.value.date,
      remark: specialForm.value.remark
    })
    
    uni.showToast({
      title: '添加成功',
      icon: 'success'
    })
    
    // 返回主页面并重置表单
    hideSpecialPage()
  } catch (error) {
    uni.showToast({
      title: error.message || '添加失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 页面加载时获取工件列表
onMounted(() => {
  fetchWorkItems()
})

// 添加下拉刷新功能
function onRefresh() {
  refreshing.value = true
  fetchWorkItems()
    .finally(() => {
      refreshing.value = false
    })
}
</script>

<style lang="scss">
.add-container {
  min-height: 100vh;
  padding: 30rpx;
  background-color: #f5f5f5;
  
  .scroll-view {
    height: calc(100vh - 60rpx);
  }
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .work-item-selector {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 20rpx;
    margin-bottom: 30rpx;
    
    .selector-input {
      height: 88rpx;
      background-color: #f8f8f8;
      border-radius: 16rpx;
      padding: 0 30rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .placeholder {
        color: #999;
        font-size: 28rpx;
      }
      
      .selected-item {
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .name {
          font-size: 28rpx;
          color: #333;
        }
        
        .price {
          font-size: 28rpx;
          color: #1296db;
        }
      }
      
      .arrow {
        color: #999;
        font-size: 24rpx;
        margin-left: 20rpx;
      }
    }
  }
  
  .picker-popup {
    background-color: #fff;
    border-radius: 30rpx 30rpx 0 0;
    
    .popup-header {
      padding: 30rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1rpx solid #f5f5f5;
      
      .title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .close {
        font-size: 40rpx;
        color: #999;
        padding: 10rpx;
      }
    }
    
    .search-box {
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #f5f5f5;
      
      input {
        height: 72rpx;
        background-color: #f8f8f8;
        border-radius: 36rpx;
        padding: 0 30rpx;
        font-size: 28rpx;
      }
    }
    
    .work-items-list {
      .work-item {
        padding: 30rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1rpx solid #f5f5f5;
        
        &.active {
          background-color: #f0f9ff;
        }
        
        .item-info {
          flex: 1;
          
          .name {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 8rpx;
            display: block;
          }
          
          .price {
            font-size: 26rpx;
            color: #1296db;
          }
        }
        
        .check-icon {
          color: #1296db;
          font-size: 32rpx;
          margin-left: 20rpx;
        }
      }
    }
    
    .popup-footer {
      padding: 30rpx;
      border-top: 1rpx solid #f5f5f5;
      
      .confirm-btn {
        background: linear-gradient(135deg, #1296db, #6bc6ff);
        color: #fff;
        height: 88rpx;
        line-height: 88rpx;
        border-radius: 44rpx;
        font-size: 32rpx;
        font-weight: bold;
      }
    }
  }
  
  .input-section {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    
    .quantity-input {
      display: flex;
      align-items: center;
      justify-content: center;
      
      .minus, .plus {
        width: 80rpx;
        height: 80rpx;
        background-color: #f5f5f5;
        border-radius: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 40rpx;
        color: #666;
        
        &:active {
          opacity: 0.7;
        }
      }
      
      input {
        width: 200rpx;
        height: 80rpx;
        text-align: center;
        font-size: 32rpx;
        margin: 0 30rpx;
      }
    }
    
    .remark-input {
      width: 100%;
      height: 200rpx;
      background-color: #f8f8f8;
      border-radius: 16rpx;
      padding: 20rpx;
      font-size: 28rpx;
    }
    
    .content-input, .hours-input {
      width: 100%;
      height: 80rpx;
      background-color: #f8f8f8;
      border-radius: 16rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
    }
  }
  
  .button-group {
    margin-top: 60rpx;
    display: flex;
    flex-direction: column;
    gap: 30rpx;
  }
  
  .submit-btn {
    background: linear-gradient(135deg, #1296db, #6bc6ff);
    color: #fff;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: bold;
    
    &[disabled] {
      opacity: 0.7;
    }
  }
  
  .special-btn {
    background-color: #fff;
    color: #1296db;
    height: 88rpx;
    line-height: 88rpx;
    border-radius: 44rpx;
    font-size: 32rpx;
    font-weight: bold;
    border: 2rpx solid #1296db;
  }
  
  .special-content {
    .page-header {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      
      .back-btn {
        display: flex;
        align-items: center;
        background: #1296db;
        color: #fff;
        padding: 12rpx 24rpx;
        border-radius: 30rpx;
        font-size: 28rpx;
        
        .back-icon {
          margin-right: 8rpx;
          font-size: 32rpx;
        }
      }
      
      .title {
        flex: 1;
        text-align: center;
        font-size: 32rpx;
        font-weight: bold;
        margin-right: 120rpx;
      }
    }

    .quantity-input,
    .price-input,
    .content-input {
      width: 100%;
      height: 80rpx;
      background-color: #f8f8f8;
      border-radius: 16rpx;
      padding: 0 20rpx;
      font-size: 28rpx;
    }

    .remark-input {
      width: 100%;
      height: 120rpx;
      background-color: #f8f8f8;
      border-radius: 16rpx;
      padding: 20rpx;
      font-size: 28rpx;
    }

    .input-section {
      margin-bottom: 20rpx;
    }
  }
}
</style> 